/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package contractmessageservice;

import java.io.StringWriter;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

/**
 *
 * @author ool
 */
public class JmsMessageService {

    public static String contractMessageToString(ContractMessage input) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(ContractMessage.class);
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(input, writer);
        return writer.toString();
    }

    public static void sendJmsMessage(String text) throws JMSException, NamingException {
        Context ctx = new InitialContext();
        ConnectionFactory connectionFactory =
                (ConnectionFactory) ctx.lookup("jms/esit1no1_ConnectionFactory");
        Queue queue = (Queue) ctx.lookup("jms/esit1no1_Queue");
        javax.jms.Connection connection = connectionFactory.createConnection();
        javax.jms.Session session =
                connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer messageProducer = session.createProducer(queue);
        TextMessage message = session.createTextMessage();
        message.setText(text);
        messageProducer.send(message);
    }
}
